
package controllers;

import java.util.Arrays;
import java.util.List;

import play.i18n.Messages;
import play.mvc.Controller;
import client.RestException;
import client.YouGoClient;

import com.ineatconseil.yougo.dto.UserTypeDto;

public class ManageUserType extends Controller {
	public static YouGoClient client = new YouGoClient();

	public static void index() throws RestException {
		List<UserTypeDto> userType = Arrays.asList(client.getUserTypeDto());
		render(userType);
	}

	public static void deleteUserType(Long userId) throws RestException {

		client.deleteUserTypeDto(userId);
		flash.success(Messages.get("manageusertype.success.delete"));
		index();
	}

	public static void edit(Long userId) throws RestException {
		UserTypeDto userType = new UserTypeDto();
		if (userId != null) {
			userType = client.getUserTypeDto(userId);
			render(userType);
		} else {
			render();
		}
	}

	/**
	 * Crée ou modifie un usertypeDTO ==> si id == null => création
	 * 
	 * @param id
	 * @param description
	 * @throws RestException 
	 */
	public static void save(Long id, String description) throws RestException {
		if (description.equals("")) {
			flash.error("La description ne peut être vide");
			edit(id);
		}
		if (id == null) {
			UserTypeDto userTypeDto = new UserTypeDto();
			userTypeDto.setDescription(description);
			client.postUserTypeDto(userTypeDto);
			flash.success(Messages.get("manageusertype.success.createupdate"));
		} else {
			UserTypeDto userTypeDto = client.getUserTypeDto(id);
			userTypeDto.setDescription(description);
			client.putUserTypeDto(userTypeDto);
			flash.success(Messages.get("manageusertype.success.createupdate"));
		}
		index();
	}
}
